package mgodb

import (
	"jgt-wallet/src/model"
	"jgt-wallet/src/schema"
	"jgt-wallet/src/service/mongo"

	"github.com/facebookgo/inject"
	"github.com/globalsign/mgo"
	"github.com/pkg/errors"
)

// cAlipayApp 日志管理表名
const cPayResult = "wallet_ali_pay_result"

// AlipayApp 日志管理
type AlipayApp struct {
	DB *mongo.DB
}

// Init 初始化
func (a *AlipayApp) Init(g *inject.Graph, db *mongo.DB) {
	a.DB = db

	// 初始化mongo索引
	a.DB.C(cPayResult, func(c *mgo.Collection) error {
		c.EnsureIndex(mgo.Index{
			Key:    []string{"_id"},
			Unique: true,
		})
		return nil
	})

	var val model.IAlipayApp = a
	g.Provide(&inject.Object{Value: val, Name: "IAlipayApp"})
}

// WritePayResult 写入支付结果
func (a *AlipayApp) WritePayResult(item *schema.AliWebPayResult) error {
	err := a.DB.C(cPayResult, func(c *mgo.Collection) error {
		id, err := a.DB.IncrID(cPayResult)
		if err != nil {
			return err
		}
		item.ID = id
		return c.Insert(item)
	})
	if err != nil {
		return errors.Wrapf(err, "创建数据发生错误")
	}

	return nil
}
